package com.sojoys.artifact.config;

import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;
import com.jfinal.plugin.IPlugin;
import com.sojoys.artifact.plugin.quartz.QuartzPlugin;
/**
 * 插件集
 * @author win7
 *
 */
final public class Plugins {
	static final Logger log = LoggerFactory.getLogger(Plugins.class);
	
	private final Map<String,IPlugin> pluginMaping = Maps.newLinkedHashMap();
	
	public Plugins add(IPlugin plugin) {
		add(plugin.getClass().getSimpleName(), plugin);
		return this;
	}
	
	public Plugins add(String pluginName,IPlugin plugin) {
		if (plugin == null) {
			throw new IllegalArgumentException("plugin can not be null");
		}
		if (pluginName == null) {
			throw new IllegalArgumentException("plugin name can not be null");
		}
		if (pluginMaping.containsKey(pluginName)) {
			throw new IllegalArgumentException("this plugin name existed"); 
		}
		pluginMaping.put(pluginName, plugin);
		return this;
	}

	public Map<String, IPlugin> getPluginMaping() {
		return pluginMaping;
	}
	
	public IPlugin getByName(String name){
		return pluginMaping.get(name);
	}
	
	
	public void plugins(boolean start) {
		if (pluginMaping.isEmpty()) {
			return ;
		}
		for (Entry<String, IPlugin> entry : pluginMaping.entrySet()) {
			try {
				boolean status = start ? entry.getValue().start() : entry.getValue().stop();
				if (!status) {
					String message = "Plugin error: " + entry.getKey();
					log.error(message);
					throw new RuntimeException(message);
				}
				log.info("Plugin -> {}",entry.getKey());
			}catch (Exception e) {
				String message = "Plugin error: " + entry.getKey() + ". \n" + e.getMessage();
				log.error(message, e);
				throw new RuntimeException(message, e);
			}
		}
	}
}